#!/usr/bin/env zsh

# Builds individual svg, uncompressed png, and quantized png images.

cmds=( 'cairosvg' 'imagemin' 'pngquant' 'xmllint')
for cmd in "${cmds[@]}"; do
  if ! type "$cmd" > /dev/null; then
    echo "Please install the command '$cmd' to build patterns"
    exit 1
  fi
done

svgdir=assets/svg
outdir=assets/png
pdir=${outdir}-uncompressed

mkdir -p $outdir $pdir

for f in $svgdir/*.svg; do
  fn=${f:t:r}.png
  out=${pdir}/${fn}
  quant=$outdir/$fn

  # Pretty-print xml and save old version in case of errors
  oldf=$f.dirty
  mv $f $oldf
  cat $oldf | xmllint --format - > $f
  if cmp $f $oldf >/dev/null 2>&1
  then
    rm -f $oldf
    # Don't rebuild PNGs if they already exist
    [[ -f $out && -f $quant ]] && continue
  else
    echo "Reformatted svg $f"
  fi

  # Build pngs
  cairosvg -f png -s 16 $f > $out
  ls -hs $out

  # Build paletted pngs for smaller file size
  cat $out | imagemin --plugin=pngquant > $quant
  ls -hs $quant

  # Display image if we have a fancy terminal
  if type "imgcat" > /dev/null; then
    # Install with `npm install -g imgcat-cli` for now
    imgcat --width 100px $out
  fi

  echo ""
done

rm -f $svgdir/*.svg.dirty
